# -*- coding:utf-8 -*-
# 京东滑块验证
import json
import requests
import base64
import pyautogui
import time, os
from PIL import Image  # Image专门处理图片的模块
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By



class JdLogin(object):
    def __init__(self):
        self.driver = webdriver.Chrome()  # 创建浏览器对象
        self.driver.get(
            "https://passport.jd.com/new/login.aspx?ReturnUrl=https%3A%2F%2Fwww.jd.com%2F%3Fcu%3Dtrue%26utm_source%3Dbaidu-pinzhuan%26utm_medium%3Dcpc%26utm_campaign%3Dt_288551095_baidupinzhuan%26utm_term%3D0f3d30c8dba7459bb52f2eb5eba8ac7d_0_9333cb81524241bbb40643e5a499e60a")
        # 设置打开浏览器窗口长和宽
        self.driver.set_window_size(1100, 900)
        time.sleep(3)

    def search_root(self):
        self.driver.find_element(By.ID, 'loginname').send_keys("15096962415")
        self.driver.find_element(By.ID, 'nloginpwd').send_keys("15096962415ZQ")
        self.driver.find_element(By.ID, 'loginsubmit').click()

    def save_img(self):
        # 创建文件夹
        if not os.path.exists("img"):
            os.mkdir("img")
        image_name = str((time.time() * 100)) + ".png"
        time.sleep(3)
        self.driver.save_screenshot("yzm.png")
        img = Image.open("yzm.png")  # 创建验证码图片处理对象

        image = img.crop((912, 284, 1257, 422))
        image.save("./img/" + image_name)

        # 打码平台验证代码
        def b64_api(username, password, img_path, ID):
            with open(img_path, 'rb') as f:
                b64_data = base64.b64encode(f.read())
            b64 = b64_data.decode()
            data = {"username": username, "password": password, "ID": ID, "b64": b64, "version": "3.1.1"}
            data_json = json.dumps(data)
            result = json.loads(requests.post("http://www.fdyscloud.com.cn/tuling/predict", data=data_json).text)
            return result

        image_path = "./img/" + image_name
        image_offset = b64_api("lyylyy", 123456, image_path, "78915616")
        print(image_offset)

        image_offset_x1 = image_offset["data"]["滑块"]["X坐标值"] + 932
        image_offset_y1 = image_offset["data"]["滑块"]["Y坐标值"] + 458


        image_offset_x2 = image_offset["data"]["缺口"]["X坐标值"] + 932 + 4.2
        image_offset_y2 = image_offset["data"]["缺口"]["Y坐标值"] + 458
        # pyautogui.moveTo(930, 458, duration=3)

        pyautogui.moveTo(image_offset_x1, image_offset_y1, duration=2)
        pyautogui.mouseDown()

        pyautogui.moveTo(image_offset_x2, image_offset_y2, duration=4)
        pyautogui.mouseUp()



        # 未成功
        # 动作链
        # ActionChains(self.driver).move_by_offset(928, 456).move_by_offset(image_offset_x1,image_offset_y1).click_and_hold().move_by_offset(image_offset_x2, image_offset_y2).release().perform()


if __name__ == '__main__':
    login = JdLogin()
    login.search_root()
    login.save_img()
